package com.ts.base.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

@Slf4j
@RestControllerAdvice(basePackages = "com.ts.base.controller")
public class GlobalExceptionHandler {

    //protected static Logger logger =null;
    @ExceptionHandler(Exception.class)
    public APIResult handleException(Exception e){
        if(e instanceof CustomException){
            //logger= LoggerFactory.getLogger(CustomException.class);

            e.printStackTrace();
            CustomException rs=(CustomException)e;

            log.error(rs.getCode()+":"+rs.getMsg()+"\r\n"+getStackTrace(e));
            return APIResult.error(rs.getCode(), rs.getMsg());
        }else{
            //logger= LoggerFactory.getLogger(Exception.class);

            e.printStackTrace();
            log.error("SYS_EXCEPTION"+":系统异常"+"\r\n"+getStackTrace(e));

            return APIResult.error("SYS_EXCEPTION","系统异常");
        }
    }

    private String getStackTrace(Exception e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
}
